package com.unbox.auth.configuration.service;
import com.unbox.admin.entity.Apps;
import com.unbox.admin.fegin.AppsFegin;
import com.unbox.common.auth.OAth2Role;
import com.unbox.common.auth.OAuth2User;
import com.unbox.common.response.UnboxResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "appManagerUserService")
@Slf4j
public class AppManagerUserServiceImpl implements UserDetailsService {

    @Autowired
    AppsFegin appsFegin;

    @Override
    public UserDetails loadUserByUsername(String appKey) throws UsernameNotFoundException {
        try {
            Apps apps = new Apps();
            apps.setAppKey(appKey);
            UnboxResponse<Apps> appsUnboxResponse = appsFegin.info(apps);
            appsUnboxResponse.checkCodeThrowExcetion();
            if (ObjectUtils.isEmpty(appsUnboxResponse.getBody())) {
                return null;
            }
            List<OAth2Role> oAth2Roles = new ArrayList<>();
            OAth2Role oAth2Role = new OAth2Role();
            oAth2Role.setId(1);
            oAth2Role.setName("admin");
            oAth2Roles.add(oAth2Role);
            OAuth2User auth2User = new OAuth2User(appKey,"", oAth2Roles);
            return auth2User;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
